﻿using System;
using System.Data;
using Common.Logging;
using InfoboardAdapterC.Common;
using InfoboardAdapterC.Properties;
using InfoboardAdapterC.RestOperation;
using NKnife.IoC;

namespace InfoboardAdapterC
{
    public class MainRunViewModel
    {
        private static readonly ILog _loggerLog = LogManager.GetLogger<MainRunViewModel>();
        private readonly InfoViewRestMessage _InfoViewRest = DI.Get<InfoViewRestMessage>();
        private readonly ParamentConfig _ParamentConfig = DI.Get<ParamentConfig>();
        private readonly SqlServerDal _ServerDb = DI.Get<SqlServerDal>();
        private System.Timers.Timer _Timer;
        private string _Connection;
        public MainRunViewModel()
        {
            InitTimer();
        }

        public void Start()
        {
            if(_Timer.Enabled)
                _Timer.Stop();
            _InfoViewRest.InitParamenet();
            RunRest();
            _Timer.Start();
        }

        public bool ConnectionHave {
            get
            {
                _ParamentConfig.LoadConnectio(out string connection);
                _Connection = connection;
                return connection.Length > 0;
            }
        }
        public void Stop()
        {
            if (_Timer.Enabled)
            _Timer.Stop();
        }

        public bool RunState => _Timer.Enabled;

        public void RunRest()
        {
            try
            {
                _InfoViewRest.RunInfoViewRest();
            }
            catch (Exception exception)
            {
                _loggerLog.Error(exception);
            }
        }

        private void InitTimer()
        {
            _Timer = new System.Timers.Timer();
            _ParamentConfig.LoadConfigTimer(out string timeTick);
            if (!int.TryParse(timeTick, out int timerV))
                timerV = 5;
            _Timer.Interval = timerV * 60 * 1000;
            _Timer.Elapsed += _Timer_Elapsed;
            _Timer.Stop();
        }

        private void _Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                _Timer.Stop();
                _InfoViewRest.RunInfoViewRest();
            }
            catch (Exception exception)
            {
               _loggerLog.Error(exception);
            }
            _Timer.Start();
        }

        public DataTable GetHidTable()
        {
            return _ServerDb.GetDataTable(Settings.Default.HushiSiteList, _Connection);
        }

        public DataTable GeTable(string hid)
        {
            try
            {
                return _InfoViewRest.GetSendValueTable(hid);
            }
            catch (Exception e)
            {

                _loggerLog.Error(e.Message);
                return null;
            }
          
        }
    }
}
